package com.example.lenovo.mywechat.homepage.find;

import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.lenovo.mywechat.R;
import com.example.lenovo.mywechat.homepage.HomepageActivity;
import com.example.lenovo.mywechat.server_config.ServerConfig;
import com.google.protobuf.ByteString;
import com.snow.proto.group_list.GroupInfo;
import com.snow.proto.group_list.GroupListInfoRequest;
import com.snow.proto.group_list.GroupListInfoResponse;
import com.snow.proto.group_list.GroupListServiceGrpc;

import java.util.ArrayList;
import java.util.List;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class FindFragment extends Fragment {


    public FindFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        TextView textView = new TextView(getActivity());
//        textView.setText(R.string.hello_blank_fragment);
//        return textView;
        return inflater.inflate(R.layout.group_list, container, false);
    }

    @Override
    public void onActivityCreated (@Nullable  Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress(ServerConfig.ip, ServerConfig.port).usePlaintext().build();
        GroupListServiceGrpc.GroupListServiceBlockingStub blockingStub = GroupListServiceGrpc.newBlockingStub(managedChannel);
        GroupListInfoResponse groupListInfoResponse = blockingStub.getGroupListInfoByUserId(GroupListInfoRequest.newBuilder().setUserId(HomepageActivity.userInfo.getId()).build());
        int count = groupListInfoResponse.getGroupInfoCount();
        List<Group> groups = new ArrayList<>();
        for(int i =0 ;i< count;i++){
            GroupInfo groupInfo = groupListInfoResponse.getGroupInfo(i);
            String name = groupInfo.getName();
            ByteString byteString = groupInfo.getAvatar();
            Group group = new Group(name,byteString);
            groups.add(group);
        }

        GroupListAdapter groupListAdapter = new GroupListAdapter(groups);
        RecyclerView recyclerView = getActivity().findViewById(R.id.group_list_layout);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(groupListAdapter);
    }
}
